﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "工单管理";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">工单管理</h3>
                </div>
                <div class="card-body">
                    <!-- 工具栏 -->
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <button type="button" class="btn btn-primary" id="btnAdd">
                                <i class="layui-icon layui-icon-add-1"></i> 新增
                            </button>
                        </div>
                    </div>

                    <!-- 数据表格 -->
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="workOrderTable">
                            <thead class="thead-light">
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" id="checkAll">
                                    </th>
                                    <th width="80">序号</th>
                                    <th>工单编号</th>
                                    <th>工单名称</th>
                                    <th>负责人ID</th>
                                    <th>订单数量</th>
                                    <th>工单描述</th>
                                    <th>创建日期</th>
                                    <th width="80">操作</th>
                                </tr>
                            </thead>
                            <tbody id="tableBody">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页控件 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="d-flex align-items-center">
                                <span id="totalCount">共 0 项数据</span>
                                <select class="form-control ml-2" id="pageSize" style="width: auto;">
                                    <option value="5">5条/页</option>
                                    <option value="10" selected>10条/页</option>
                                    <option value="20">20条/页</option>
                                    <option value="50">50条/页</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <nav aria-label="分页导航">
                                <ul class="pagination justify-content-end" id="pagination">
                                    <!-- 分页按钮将通过JavaScript动态生成 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalCount = 0;
        let workOrderData = [];

        // 初始化页面
        initPage();

        // 绑定事件
        bindEvents();

        // 初始化页面
        function initPage() {
            loadWorkOrderData();
        }

        // 绑定事件
        function bindEvents() {
            // 每页显示数量变化事件
            $('#pageSize').change(function () {
                pageSize = parseInt($(this).val());
                currentPage = 1;
                loadWorkOrderData();
            });

            // 全选/取消全选
            $('#checkAll').change(function () {
                $('input[name="rowCheck"]').prop('checked', $(this).prop('checked'));
            });

            // 新增按钮
            $('#btnAdd').click(function () {
                window.location.href = '/Home/AddWorkOrder';
            });
        }

        // 加载工单数据
        function loadWorkOrderData() {
            // 显示加载状态
            showLoading();
            
            // 调用后端API
            $.ajax({
                url: 'http://localhost:5025/api/Production/GetWorkOrder',
                type: 'GET',
                data: {
                    page: currentPage,
                    pageSize: pageSize
                },
                success: function (response) {
                    hideLoading();
                    if (response.code === 200) {
                        workOrderData = response.data || [];
                        totalCount = workOrderData.length; // 实际项目中应该从后端获取总数
                        renderTable();
                        renderPagination();
                    } else {
                        showError('加载数据失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLoading();
                    showError('请求失败：' + error);
                }
            });
        }

        // 渲染表格
        function renderTable() {
            const tbody = $('#tableBody');
            tbody.empty();

            if (workOrderData.length === 0) {
                tbody.append('<tr><td colspan="9" class="text-center">暂无数据</td></tr>');
                return;
            }

            workOrderData.forEach((item, index) => {
                const row = `
                    <tr>
                        <td>
                            <input type="checkbox" name="rowCheck" value="${item.workOrderId}">
                        </td>
                        <td>${(currentPage - 1) * pageSize + index + 1}</td>
                        <td>${item.workOrderCode || ''}</td>
                        <td>${item.workOrderName || ''}</td>
                        <td>${item.leaderId || ''}</td>
                        <td>${item.orderNum || ''}</td>
                        <td>${item.worderOrderDesc || ''}</td>
                        <td>${formatDate(item.workOrderDate)}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-info" onclick="viewWorkOrder(${item.workOrderId})">
                                查看
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });

            // 更新总数显示
            $('#totalCount').text(`共 ${totalCount} 项数据`);
        }

        // 渲染分页
        function renderPagination() {
            const totalPages = Math.ceil(totalCount / pageSize);
            const pagination = $('#pagination');
            pagination.empty();

            if (totalPages <= 1) {
                return;
            }

            // 上一页
            const prevDisabled = currentPage === 1 ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${prevDisabled}">
                    <a class="page-link" href="#" onclick="goToPage(${currentPage - 1})">‹</a>
                </li>
            `);

            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const active = i === currentPage ? 'active' : '';
                pagination.append(`
                    <li class="page-item ${active}">
                        <a class="page-link" href="#" onclick="goToPage(${i})">${i}</a>
                    </li>
                `);
            }

            // 下一页
            const nextDisabled = currentPage === totalPages ? 'disabled' : '';
            pagination.append(`
                <li class="page-item ${nextDisabled}">
                    <a class="page-link" href="#" onclick="goToPage(${currentPage + 1})">›</a>
                </li>
            `);
        }



        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false });
        }

        // 显示加载状态
        function showLoading() {
            $('#tableBody').html('<tr><td colspan="9" class="text-center"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...</td></tr>');
        }

        // 隐藏加载状态
        function hideLoading() {
            // 加载完成后会重新渲染表格
        }

        // 显示错误信息
        function showError(message) {
            $('#tableBody').html(`<tr><td colspan="9" class="text-center text-danger">${message}</td></tr>`);
        }

        // 将函数暴露到全局，便于分页和按钮点击使用
        window.goToPage = function (page) {
            if (page < 1) return;
            currentPage = page;
            loadWorkOrderData();
        };

        window.viewWorkOrder = function (id) {
            window.location.href = `/Home/GetWorkOrderDetail?id=${id}`;
        };


    });
</script>

<style>
    .card {
        margin: 20px;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .table th {
        background-color: #f8f9fa;
        border-color: #dee2e6;
    }
    
    .badge {
        font-size: 0.75em;
    }
    
    .pagination .page-link {
        color: #007bff;
    }
    
    .pagination .page-item.active .page-link {
        background-color: #007bff;
        border-color: #007bff;
    }
    
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    
    .layui-icon {
        font-size: 14px;
    }
</style>

